from datetime import datetime

from flask import current_app
from flask import g
from flask import request, jsonify

from info import db
from info.models import House, Order
from info.utils.common import pro_blue
from . import orders_blue
@orders_blue.route('/api/v1.0/orders',methods=['POST','GET','PUT'])
@pro_blue
def oredrs():
    if not g.user:
        return jsonify(errno=1,errmsg='用户未登陆')
    if request.method=='POST':
        #创建订单
        house_id=request.json.get('house_id')
        start_date=request.json.get('start_date')
        end_date=request.json.get('end_date')
        if not all([house_id,start_date,end_date]):
            return jsonify(errno=1,errmsg='参数不全')
        house=House.query.filter(House.id==int(house_id)).first()
        if not house:
            return jsonify(errno=1,errmsg='该房屋不存在')
        if g.user.id==house.user_id:
            return jsonify(errno=1,errmsg="不能预定自己的房子")
        sd=datetime.strptime(start_date,'%Y-%m-%d')
        ed = datetime.strptime(end_date,'%Y-%m-%d')
        de=ed-sd
        de_time=de.days
        if (not de_time) or (de_time<=0):
            return jsonify(errno=1,errmsg='时间参数错误')
        if de_time < house.min_days:
            return jsonify(errno=1, errmsg='不能小于最小租房时间')
        if house.max_days:
            if de_time>house.max_days:
                return jsonify(errno=1, errmsg='不能小于最小租房时间')
        order_list=house.orders
        for i in order_list:
            if (sd>i.begin_date and sd <i.end_date) or (ed>i.begin_date and ed <i.end_date):
                return jsonify(errno=1, errmsg='该时间段已有订单')
        order=Order()
        order.user_id=g.user.id
        order.house_id=house.id
        order.begin_date=sd
        order.end_date=ed
        order.days=de_time
        order.house_price=house.price
        order.amount=house.price*de_time
        db.session.add(order)
        db.session.commit()
        data={
            'order_id':order.id
        }
        return jsonify(errno=0, errmsg='ok',data=data)
    if request.method=='GET':               #获得订单列表
        role=request.args.get('role')
        if not role:
            return jsonify(errno=1, errmsg='参数不全')
        orders_list=[]
        if role=='custom':
            orders_list=g.user.orders
        if role=='landlord':
            house_id_list = []
            house_list = g.user.houses
            for i in house_list:
                house_id_list.append(i.id) if i else ''
            orders_list=Order.query.filter(Order.house_id in house_id_list).all()
        order_dict_list=[]
        for i in orders_list:
            order_dict_list.append(i.to_dict())
        data={
            "orders":order_dict_list
        }
        return jsonify(errno=0, errmsg='ok',data=data)
    if request.method=='PUT':           #接单和拒单
        action=request.json.get('action')
        order_id=request.json.get('order_id')
        reason=request.json.get('reason')
        if not all([action,order_id]):
            return jsonify(errno=1, errmsg='参数不全')
        try:
            order=Order.query.filter(Order.id==int(order_id))
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=1, errmsg='操作失败')
        if not order:
            return jsonify(errno=1, errmsg='订单不存在')
        if action=='accept':
            order.status="WAIT_PAYMENT"
        if action=='reject':
            if reason:
                order.status = "REJECTED"
                order.comment=reason
            else:
                return jsonify(errno=1, errmsg='拒单原因不存在')
        db.session.commit()
        return jsonify(errno=0,errmsg='ok')
@orders_blue.route('/api/v1.0/orders/comment',methods=['PUT'])
@pro_blue
def comments():
    if not g.user:
        return jsonify(errno=1, errmsg='用户未登陆')
    comment=request.json.get('comment')
    order_id=request.json.get('order_id')
    if not all([comment, order_id]):
        return jsonify(errno=1, errmsg='参数不全')
    try:
        order = Order.query.filter(Order.id == int(order_id))
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=1, errmsg='操作失败')
    if not order:
        return jsonify(errno=1, errmsg='订单不存在')
    order.comment=comment
    db.session.commit()
    return jsonify(errno=0, errmsg='ok')





